import React, { useEffect, useRef, useState } from "react";
import { Form, Input, Button, Checkbox, Cascader, Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import "../../static/css/School/SchoolAddUp.css"
import { postAdd, postUp } from "../../apis/school/addUp";
import { useLocation, useNavigate } from "react-router";
import { useSearchParams } from "react-router-dom";
import MyEditor from '../../components/Editor'

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};

const SchoolAddUp: React.FC = (): JSX.Element => {
    const echo: any = useRef()
    const { state }: any = useLocation()
    const navigate = useNavigate()
    const { TextArea } = Input;
    const [form] = Form.useForm();
    const [content,setContent]=useState()

    // 调用修改接口
    const upInfo = async (id: number, params: any) => {
        const res: any = await postUp(id, params)
        if (res.code === '00000') {
            message.success("修改成功");
            navigate('/school/list')
        } else {
            message.error(res.msg)
        }

    }
    useEffect(() => {
        echo.current.setFieldsValue(state)
        if (state) {
            setImageUrl(state.thumb)
        }

    }, [])
    // 调用添加接口
    const addInfo = async (params: any) => {
        const res: any = await postAdd(params)
        if (res.code === '00000') {
            message.success("添加成功");
            navigate('/school/list')
        } else {
            message.error(res.msg)
        }

    }
    // 点击添加
    const onFinish = (values: any) => {
        // console.log('Success:', values);
        const params = { ...values, thumb: imageUrl,content }
        if (state) {
            upInfo(state.news_id, params)
        } else {
            addInfo(params)
        }



    };
    const onReset = () => {
        form.resetFields();
    };
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();

    const handleChange: UploadProps['onChange'] = (info: any) => {
        // console.log(info);

        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            let url = info.fileList[0].response.data.src
            setImageUrl(url);

        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    const normFile = () => {

    }
    const editorValue:any=(props:any)=>{
            setContent(props)
    }
    const token: any = sessionStorage.getItem('token')
    return (
        <div className="schoolAddUpBody">
            <div className="type">
                {
                    state ? <h3>修改</h3> : <h3>添加</h3>
                }

            </div>
            <div className="form">
                <Form
                    name="basic"
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 6 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    autoComplete="off"
                    form={form}
                    ref={echo}
                >
                    <Form.Item
                        label="标题"
                        name="title"
                        rules={[{ required: true, message: '请输入标题' }]}
                    >
                        <Input size="small" />
                    </Form.Item>
                    <Form.Item
                        label="关键字"
                        name="keywords"
                        rules={[{ required: true, message: '请输入关键字' }]}
                    >
                        <Input size="small" />
                    </Form.Item>
                    <Form.Item
                        label="作者"
                        name="author"
                        rules={[{ required: true, message: '请输入作者' }]}
                    >
                        <Input size="small" />
                    </Form.Item>
                    <Form.Item
                        label="介绍"
                        name="desc"
                        rules={[{ required: true, message: '请填写介绍' }]}
                    >
                        <TextArea rows={2} />
                    </Form.Item>
                    <Form.Item
                        label="缩略图"
                        name="thumb"
                    // // 以下两条是必须的
                    // valuePropName="fileList"
                    // // 如果没有下面这一句会报错
                    // getValueFromEvent={normFile}
                    >
                        <Upload
                            name="file"
                            headers={{ Authorization: token }}
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="http://121.42.230.80/api/visit/upload"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}

                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        label="正文"
                        name="content"
                    >
                        <MyEditor editorValue={editorValue} content={state? state.content:''}></MyEditor>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 3, span: 6 }}>
                        <Button htmlType="button" onClick={onReset} style={{ backgroundColor: '#909399', color: '#fff', border: 'none', marginRight: '10px' }}>
                            重置
                        </Button>
                        <Button type="primary" htmlType="submit" style={{ border: 'none' }}>
                            确定
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )

}
export default SchoolAddUp